package provider

import (
	"time"
	"net/http"
	"log"
	"encoding/json"
	"io/ioutil"
	"github.com/kingwrcy/devNews/model"
	"crypto/sha1"
	"fmt"
)

type JueJinProvider struct{}

func (p *JueJinProvider) Schedule() time.Duration {
	return time.Minute * 10
}

func (p *JueJinProvider) Name() string{
	return "jueJin"
}

func (p *JueJinProvider) GetData(t time.Time) []model.News {
	url := "https://timeline-merger-ms.juejin.im/v1/get_entry_by_rank?src=web&before=0&limit=20&category=5562b419e4b00c57d9b94ae2"
	resp, err := http.Get(url)
	if err != nil {
		log.Printf("get %s error : %s", url, err)
		return nil
	}
	defer resp.Body.Close()
	b, _ := ioutil.ReadAll(resp.Body)
	m := model.JueJinModel{}
	err = json.Unmarshal(b, &m)
	if err != nil {
		log.Printf("Unmarshal error : %s", err)
		return nil
	}
	news := []model.News{}
	for _, e := range m.D.Entrylist {

		h := sha1.New()
		h.Write([]byte(fmt.Sprintf("%s%s", e.Title, e.OriginalURL)))
		uuid := fmt.Sprintf("%x", h.Sum(nil))
		n := model.News{
			Title:   e.Title,
			Created: time.Time(e.UpdatedAt),
			Url:     e.OriginalURL,
			Source:  JueJinSource,
			Uuid:    uuid,
		}
		news = append(news, n)
	}
	return news
}
